package com.movie.service;

import com.movie.dto.RoleDTO;
import com.movie.dto.SystemUserDTO;
import com.movie.entity.SysUser;
import com.movie.repository.SystemUserRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class SystemUserService {
    
    private final SystemUserRepository userRepository;
    private final PasswordEncoder passwordEncoder;
    
    public List<SystemUserDTO> findAll() {
        return userRepository.findAll()
                .stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }
    
    public Page<SystemUserDTO> findAll(Pageable pageable) {
        return userRepository.findAll(pageable)
                .map(this::convertToDTO);
    }
    
    public Page<SystemUserDTO> findByKeyword(String keyword, Pageable pageable) {
        if (keyword == null || keyword.trim().isEmpty()) {
            return userRepository.findAll(pageable)
                    .map(this::convertToDTO);
        }
        
        // 使用自定义查询进行分页搜索
        return userRepository.findByUsernameOrEmailContaining(keyword, pageable)
                .map(this::convertToDTO);
    }
    
    public SystemUserDTO findById(Long id) {
        SysUser user = userRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("用户不存在"));
        return convertToDTO(user);
    }
    
    @Transactional
    public SystemUserDTO create(SystemUserDTO userDTO) {
        // 检查用户名是否已存在
        if (userRepository.existsByUsername(userDTO.getUsername())) {
            throw new RuntimeException("用户名已存在");
        }
        
        // 检查邮箱是否已存在
        if (userRepository.existsByEmail(userDTO.getEmail())) {
            throw new RuntimeException("邮箱已存在");
        }

        SysUser user = convertToEntity(userDTO);
        user.setPassword(passwordEncoder.encode(userDTO.getPassword()));
        SysUser saved = userRepository.save(user);
        return convertToDTO(saved);
    }
    
    @Transactional
    public SystemUserDTO update(Long id, SystemUserDTO userDTO) {
        SysUser existing = userRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("用户不存在"));
        
        // 检查用户名是否被其他用户使用
        if (!existing.getUsername().equals(userDTO.getUsername()) && 
            userRepository.existsByUsername(userDTO.getUsername())) {
            throw new RuntimeException("用户名已存在");
        }
        
        // 检查邮箱是否被其他用户使用
        if (!existing.getEmail().equals(userDTO.getEmail()) && 
            userRepository.existsByEmail(userDTO.getEmail())) {
            throw new RuntimeException("邮箱已存在");
        }
        
        BeanUtils.copyProperties(userDTO, existing, "id", "password", "createdAt", "updatedAt");
        
        // 如果提供了新密码，则加密更新
        if (userDTO.getPassword() != null && !userDTO.getPassword().isEmpty()) {
            existing.setPassword(passwordEncoder.encode(userDTO.getPassword()));
        }
        
        SysUser updated = userRepository.save(existing);
        return convertToDTO(updated);
    }
    
    @Transactional
    public void delete(Long id) {
        SysUser user = userRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("用户不存在"));
        userRepository.delete(user);
    }
    
    @Transactional
    public SystemUserDTO toggleStatus(Long id) {
        SysUser user = userRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("用户不存在"));
        user.setStatus(!user.getStatus());
        SysUser updated = userRepository.save(user);
        return convertToDTO(updated);
    }
    
    @Transactional
    public void updateLastLogin(Long id) {
        SysUser user = userRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("用户不存在"));
        user.setLastLogin(LocalDateTime.now());
        userRepository.save(user);
    }
    
    public List<SystemUserDTO> findByRole(String roleName) {
        // 由于User实体已改为多角色，此方法需要重新实现
        // 暂时返回空列表，需要根据具体业务需求实现
        return List.of();
    }
    
    public List<SystemUserDTO> findByStatus(Boolean status) {
        return userRepository.findByStatus(status)
                .stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }
    
    public SystemUserDTO findByUsername(String username) {
        SysUser user = userRepository.findByUsername(username)
                .orElseThrow(() -> new RuntimeException("用户不存在"));
        return convertToDTO(user);
    }
    
    public SystemUserDTO findByEmail(String email) {
        SysUser user = userRepository.findByEmail(email)
                .orElseThrow(() -> new RuntimeException("用户不存在"));
        return convertToDTO(user);
    }
    
    private SystemUserDTO convertToDTO(SysUser user) {
        SystemUserDTO dto = new SystemUserDTO();
        BeanUtils.copyProperties(user, dto);
        
        // 转换角色列表
        if (user.getRoles() != null) {
            List<RoleDTO> roleDTOs = user.getRoles().stream()
                    .map(role -> {
                        RoleDTO roleDTO = new RoleDTO();
                        BeanUtils.copyProperties(role, roleDTO);
                        return roleDTO;
                    })
                    .collect(Collectors.toList());
            dto.setRoles(roleDTOs);
        }
        
        return dto;
    }
    
    private SysUser convertToEntity(SystemUserDTO dto) {
        SysUser user = new SysUser();
        BeanUtils.copyProperties(dto, user);
        return user;
    }
}